package com.roamer.audition.web.security.handler;

import com.roamer.audition.web.security.service.JwtUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出登陆处理器
 * 清理Token
 *
 * @author roamer
 * @version v1.0
 * @date 2020/4/20 18:08
 */
public class LogoutClearTokenHandler implements LogoutHandler {

    private JwtUserService jwtUserService;

    public LogoutClearTokenHandler(JwtUserService jwtUserService) {
        this.jwtUserService = jwtUserService;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        clearToken(authentication);
    }

    protected void clearToken(Authentication authentication) {
        if (authentication == null)
            return;
        UserDetails user = (UserDetails) authentication.getPrincipal();
        if (user != null && user.getUsername() != null) {
            jwtUserService.clearToken(user.getUsername());
        }
    }
}
